package com.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class Dom4jUtil {
	
	@SuppressWarnings("rawtypes")
	public static Map<String, String> getMessageCode(String xml) throws DocumentException{
		 Map<String, String> map=new HashMap<String, String>();
		 Document document = DocumentHelper.parseText(xml);  
		 Element root = document.getRootElement(); 
		 Element codeElement=root.element("code");
		 Element messageElement=root.element("message");
		 String code=codeElement.getText();
		 map.put("code", code);
		 if(messageElement!=null){
			 for(Iterator it=messageElement.elementIterator();it.hasNext();){          
		           Element element = (Element) it.next();           
		           String text=element.getText();
		           String key=element.getName();
		           map.put(key, text);
			 }
		 }
		 return map;
	}
	
	
	//<?xml version="1.0" encoding="gbk" ?><response><code>04</code></response><?xml version="1.0" encoding="gbk"?>
	//<response><code>03</code><message><desmobile>13900000000</desmobile><msgid>200811041234253654785</msgid></message></response>
	public static void main(String[] args) throws DocumentException {
		Map<String, String> maps=Dom4jUtil.getMessageCode("<response><code>03</code><message><desmobile>13900000000</desmobile><msgid>200811041234253654785</msgid></message></response>");
		System.err.println(maps);
	}
}
